package com.proj.controller;

import com.proj.util.LayData;
import com.proj.util.SYS;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class UploadController {

    @RequestMapping("uploader")
    public String upload(){
        return "upload.html";
    }

    @RequestMapping("upload")
    @ResponseBody
    public LayData upload(@RequestParam("file") MultipartFile file) {
        //获取文件原来的后缀名
            //原来的名字
        String filename = file.getOriginalFilename();
            //获取后缀名
        String fileType = filename.substring(filename.lastIndexOf(".") + 1);
        //在前面拼接上一个新的名字，这个名字尽量不重复

        //***雪花算法***
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + "." + fileType;
        //将这个名字写入到新文件中
        try {
            file.transferTo(new File(SYS.FILE_UPLOAD_DIR+newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }



        //返回结果


        return new LayData(SYS.FILE_UPLOAD_URL+"/"+newFileName);
    }
}
